package com.shxy.rlzy.service.impl;

import com.shxy.rlzy.entity.Menu;
import com.shxy.rlzy.entity.Role;
import com.shxy.rlzy.mapper.MenuMapper;
import com.shxy.rlzy.mapper.UserRoleMapper;
import com.shxy.rlzy.service.IAuthoritySerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuthoritySerivceImpl implements IAuthoritySerivce {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public String getAuthoritiesByUserId(Long userId) {
        String authorities = "";
        // 获取角色
        List<Role> roles = userRoleMapper.selectRolesOfUser(userId);

        // 将角色名称进行格式转换
        if(roles.size() > 0) {
            String roleCodes = roles.stream().map(role -> "ROLE_" + role.getCode()).collect(Collectors.joining(","));
            authorities = roleCodes;
        }

        // 获取用户能访问的菜单列表
        List<Long> menuIds = menuMapper.getUserMenus(userId).stream().map(Menu::getId).toList();

        if(menuIds.size() > 0) {
            List<Menu> menus = menuMapper.selectBatchIds(menuIds);
            String menuPerms = menus.stream().map(menu -> menu.getPerms()).collect(Collectors.joining(","));

            authorities = authorities.concat(",").concat(menuPerms);
        }
        return authorities;
    }
}
